package com.example.doubledatasource.converter;

import com.example.doubledatasource.dto.ProductDTO;
import com.example.doubledatasource.entity.Product;
import com.example.doubledatasource.vo.ProductVO;
import org.mapstruct.*;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Locale;

/**
 * 产品对象转换器 - 使用MapStruct
 * 负责Product、ProductDTO、ProductVO之间的转换
 *
 * @author example
 * @since 1.0.0
 */
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING,
        nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE,
        unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface ProductConverter {

    DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    NumberFormat CURRENCY_FORMAT = NumberFormat.getCurrencyInstance(Locale.CHINA);

    /**
     * Entity转VO
     */
    @Mapping(target = "priceStr", source = "price", qualifiedByName = "formatPrice")
    @Mapping(target = "stockStatusText", source = "stock", qualifiedByName = "getStockStatusText")
    @Mapping(target = "createTimeStr", source = "createTime", qualifiedByName = "formatDateTime")
    @Mapping(target = "updateTimeStr", source = "updateTime", qualifiedByName = "formatDateTime")
    ProductVO toVO(Product product);

    /**
     * DTO转Entity
     */
    @Mapping(target = "id", ignore = true)
    @Mapping(target = "createTime", expression = "java(java.time.LocalDateTime.now())")
    @Mapping(target = "updateTime", expression = "java(java.time.LocalDateTime.now())")
    Product toEntity(ProductDTO dto);

    /**
     * 更新Entity（用于更新操作）
     */
    @Mapping(target = "id", ignore = true)
    @Mapping(target = "createTime", ignore = true)
    @Mapping(target = "updateTime", expression = "java(java.time.LocalDateTime.now())")
    void updateEntity(@MappingTarget Product product, ProductDTO dto);

    /**
     * Entity列表转VO列表
     */
    List<ProductVO> toVOList(List<Product> products);

    /**
     * 格式化价格
     */
    @Named("formatPrice")
    default String formatPrice(BigDecimal price) {
        return price != null ? CURRENCY_FORMAT.format(price) : null;
    }

    /**
     * 获取库存状态文本
     */
    @Named("getStockStatusText")
    default String getStockStatusText(Integer stock) {
        if (stock == null || stock <= 0) {
            return "缺货";
        } else if (stock <= 10) {
            return "库存紧张";
        } else {
            return "有库存";
        }
    }

    /**
     * 格式化日期时间
     */
    @Named("formatDateTime")
    default String formatDateTime(LocalDateTime dateTime) {
        return dateTime != null ? dateTime.format(DATE_TIME_FORMATTER) : null;
    }
}
